import 'dart:convert';
import 'dart:developer';
import 'dart:math' hide log;

import 'package:im_base/public/ext/string_ext.dart';
import 'package:im_base/public/global/custom_bean.dart';
import 'package:im_base/public/global/global.dart';
import 'package:tencent_im_sdk_plugin/enum/message_elem_type.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_custom_elem.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_image.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_image_elem.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_text_elem.dart';

///@author:create by BZY
///Date: 2021/8/6 17:00
///Description:图文问诊消息model类,[fromAccount] 始终为患者信息
class MessageHistoryModel {
  String fromAccount;
  String? fromImg;
  String? fromName;
  String? inquiryId;
  String? msgContent;
  String? msgTime;
  String? msgType;
  String? toAccount;
  String? toHeadImg;
  String? toName;

  MessageHistoryModel({required this.fromAccount,
    this.fromImg,
    this.fromName,
    this.inquiryId,
    this.msgContent,
    this.msgTime,
    this.msgType,
    this.toAccount,
    this.toHeadImg,
    this.toName});

  String get msgId {
    return '${DateTime
        .now()
        .microsecondsSinceEpoch}${Random().nextInt(99999)}';
  }

  ///将model类转换为腾讯云消息[sender]因为[fromAccount]始终为患者,所以这里进行判断,如果当前用户为患者,则发送方是患者,否则为医生
  V2TimMessage convertToMessage() {
    ///当前账号登录的是否为医生
    var isDoctor = Global.IDENTIFIER.contains('doc');

    ///该条信息是否为医生发送的
    var isSenderDoctor = fromAccount.contains('doc');
    return V2TimMessage(
        elemType: getElemType(),
        msgID: msgId,
        timestamp:
        (DateTime
            .parse(msgTime!)
            .millisecondsSinceEpoch / 1000).floor(),
        sender: fromAccount,
        faceUrl: fromImg,
        nickName: fromName,
        userID: fromAccount,
        textElem: getTextElem(),
        imageElem: getImageElem(),
        customElem: getCustomElem(),
        isSelf: (Global.IDENTIFIER.contains('pat') &&
            Global.IDENTIFIER == fromAccount) ||
            (Global.IDENTIFIER.contains('doc') &&
                Global.IDENTIFIER == toAccount),
        isRead: true,
        isPeerRead: true);
  }

  ///获取文字类型的消息数据
  V2TimTextElem? getTextElem() {
    if (getElemType() == MessageElemType.V2TIM_ELEM_TYPE_TEXT) {
      return V2TimTextElem(text: getContent()['MsgContent']['Text']);
    }
    return null;
  }

  ///获取文字类型的消息数据
  ///这里因为后台返回的数据格式问题,不能直接解析使用,自己封装json,只使用msg作为类型判断
  V2TimCustomElem? getCustomElem() {
    if (getElemType() == MessageElemType.V2TIM_ELEM_TYPE_CUSTOM) {
      var dataMap = jsonDecode(formatJson(msgContent))[0]['MsgContent'];
      var custom = (dataMap['Ext'] as String).isNullEmpty()
          ? dataMap['Data']
          : dataMap['Ext'];

      if (custom != null && (custom as String).isNotEmpty) {
        var customJson = formatJson(custom).toString();
        if (!customJson.contains('"')) {
          customJson =
              customJson.replaceAll('{', '{"').replaceAll('}', '"}').replaceAll(
                  ':', '":"').replaceAll(',', '","');
        }
        var bean = CustomBean.fromMap(jsonDecode(customJson));
        log(formatJson(custom));
        return V2TimCustomElem(
            data: formatJson(custom));
      }
    }
    return null;
  }

  ///获取图片类型的消息数据
  V2TimImageElem? getImageElem() {
    if (getElemType() == MessageElemType.V2TIM_ELEM_TYPE_IMAGE) {
      return V2TimImageElem(
          imageList: (getContent()['MsgContent']['ImageInfoArray'] as List)
              .map((e) =>
              V2TimImage(
                  type: e['Type'],
                  size: e['Size'],
                  width: e['Width'],
                  height: e['Height'],
                  url: e['URL']))
              .toList());
    }
    return null;
  }

  Map<String, dynamic> getContent() {
    String? data = msgContent
        ?.replaceAll('\\', '')
        .replaceFirst('[', '');
    data = data?.substring(0, data.length - 1);
    try {
      return jsonDecode(data ?? '');
    } on Exception catch (e) {
      return {};
    }
  }

  ///转换消息类型
  int getElemType() {
    switch (msgType) {
      case 'TIMTextElem':
        return MessageElemType.V2TIM_ELEM_TYPE_TEXT;
      case 'TIMImageElem':
        return MessageElemType.V2TIM_ELEM_TYPE_IMAGE;
      case 'TIMCustomElem':
        return MessageElemType.V2TIM_ELEM_TYPE_CUSTOM;
    // case 'TIMSoundElem':
    //   return MessageElemType.V2TIM_ELEM_TYPE_SOUND;
      default:
        return MessageElemType.V2TIM_ELEM_TYPE_NONE;
    }
  }

  factory MessageHistoryModel.fromJson(Map<String, dynamic> json) {
    return MessageHistoryModel(
      fromAccount: json['fromAccount'],
      fromImg: json['fromImg'],
      fromName: json['fromName'],
      inquiryId: json['inquiryId'],
      msgContent: json['msgContent'],
      msgTime: json['msgTime'],
      msgType: json['msgType'],
      toAccount: json['toAccount'],
      toHeadImg: json['toHeadImg'],
      toName: json['toName'],
    );
  }

  Map<String, dynamic> toJson() {
    var data = <String, dynamic>{};
    data['fromAccount'] = fromAccount;
    data['fromImg'] = fromImg;
    data['fromName'] = fromName;
    data['inquiryId'] = inquiryId;
    data['msgContent'] = msgContent;
    data['msgTime'] = msgTime;
    data['msgType'] = msgType;
    data['toAccount'] = toAccount;
    data['toHeadImg'] = toHeadImg;
    data['toName'] = toName;
    return data;
  }
}

